package com.yunshan.oss;

import com.yunshan.common.core.domain.AjaxResult;
import com.yunshan.common.exception.ServiceException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import static com.yunshan.common.core.domain.AjaxResult.success;
import static com.yunshan.framework.datasource.DynamicDataSourceContextHolder.log;

@Api(tags = "oss上传文件")
@RestController
@RequestMapping("/oss/file")
public class OssFileController {
    @Resource
    private OssFileService ossFileService;

    @ApiOperation(value = "Oss上传签名生成")
    @GetMapping(value = "/policy")
    public OssPolicyResult policy() {
        OssPolicyResult result = ossFileService.policy();
        return result;
    }

    @ApiOperation(value = "Oss上传成功回调")
    @PostMapping(value = "/callback")
    public OssCallbackResult callback(HttpServletRequest request) {
        OssCallbackResult ossCallbackResult = ossFileService.callback(request);
        return  ossCallbackResult;
    }


    @ApiOperation("文件上传")
    @PostMapping("/upload/image")
    public AjaxResult uploadFile(MultipartFile file, String dir) {
        try {
            return success(upload(file, dir));
        }catch (Exception e){
            log.error("上传失败：{}", e.getMessage());
            return AjaxResult.error("上传失败");
        }
    }

    private  Object upload(MultipartFile file, String dir) {
        String directory= "admin/image";
        if (dir != null) {
            directory += "/" + dir;
        }
        String url = ossFileService.uploadFile(directory, "", file);
        if (url != null) {
            return url;
        } else {
            throw new ServiceException("上传失败");
        }
    }
}
